// Author: wsfuyibing <682805@qq.com>
// Date: 2025-04-28

package services

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"math/rand"
	"server/app/http/models"
	"server/app/kind"
)

// Apply
// 申请二维码.
func (o *QrcodeService) Apply(ctx context.Context, typ kind.QrcodeType, uid kind.UserId, params map[string]any) (model *models.Qrcode, err error) {
	var (
		can, has bool
		sess     *db.Session
		setting  = typ.Setting()
	)

	// 1. 获取连接.
	if sess, err = o.Dao.Master(ctx); err != nil {
		return
	}

	// 2. 查询申请.
	model = &models.Qrcode{}

	// 2.1 查询过程.
	if has, err = sess.Where("`type` = ? AND `user_id` = ?", typ, uid).OrderBy(`created_at DESC`).Get(model); err != nil {
		return
	}

	// 2.2. 存在申请.
	//      若上次申请的二维码还能继续使用, 则直接复用, 无需创建.
	if has {
		if can, _ = model.CanUse(); can {
			_, err = o.UpdateAppliedCount(ctx, model)
			return
		}
	}

	// 3. 准备创建.
	model = &models.Qrcode{
		Sign:         fmt.Sprintf(`S%5d`, rand.Int31n(99999)),
		Type:         typ,
		UserId:       uid,
		Timeout:      setting.Timeout,
		ScannedLimit: setting.Limit,
	}

	// 3.1 参数.
	if params != nil {
		if b, be := json.Marshal(params); be == nil {
			model.Params = string(b)
		}
	}

	// 3.2 创建过程.
	_, err = sess.Insert(model)
	return
}

func (o *QrcodeService) UpdateAppliedCount(ctx context.Context, bean *models.Qrcode) (affects int64, err error) {
	var sess *db.Session
	if sess, err = o.Dao.Master(ctx); err == nil {
		bean.AppliedAt = db.Now()
		affects, err = sess.Cols("applied_count", "applied_at").Incr("applied_count").Where("`id` = ?", bean.Id).Update(bean)
	}
	return
}

func (o *QrcodeService) UpdateScannedCount(ctx context.Context, bean *models.Qrcode) (affects int64, err error) {
	var sess *db.Session
	if sess, err = o.Dao.Master(ctx); err == nil {
		affects, err = sess.Cols("scanned_count").Incr("scanned_count").Where("`id` = ?", bean.Id).Update(bean)
	}
	return
}
